<template>
    <el-card class="my-20px">
        <filterComponent v-model:filter-data="filterData" @doSearch="handleSearch" />
    </el-card>
    <el-card>
        <tableComponent class="set-height" :table-header="tableHeader" :table-data="tableData" v-model:page-info="pageInfo"
            @pageChange="handlePageChange" @sort-change="sortMethod">
            <template #isMonthMode>
                <el-table-column label="月单模式" width="120">
                    <template #default="scope">
                        <!-- <span v-if="scope.row.isFlexible" class="mg-r-5">灵活保单</span>
                        <span v-if="scope.row.isImmediate" class="mg-r-5">即时生效</span>
                        <span v-if="scope.row.isMonth">月单</span> -->
                        <span>{{ monthModeName(scope.row.type) }}</span>
                    </template>
                </el-table-column>
            </template>
            <template #operationType>
                <el-table-column label="操作类型" width="120">
                    <template #default="scope">
                        <span :class="[`type-${scope.row.operationType}`]">{{ operationName(scope.row.operationType) }}</span>
                    </template>
                </el-table-column>
            </template>
            <template #settings>
                <el-table-column fixed="right" label="操作" width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="toDetail(scope.row)">查看详情</el-button>
                    </template>
                </el-table-column>
            </template>
        </tableComponent>
    </el-card>
</template>
<script setup>
import { ref, computed, onMounted, onActivated } from 'vue'
import filterComponent from '@/components/filterComponent/index.vue'
import tableComponent from '@/components/tableComponent/index.vue'
import { getPolicyList, getInsuranceCompany, getAddAndSubtractList, getInsureMode } from '@/api/dashboard/longTerm.ts'
import { useRouter } from 'vue-router'
import { getdepartmentapi } from '@/api/api.ts'
import { getDealList, getDeptList, getSalesmanList, getProductList } from '@/api/clients/signClient.ts'

const router = useRouter()
import dayjs from 'dayjs'
const startDate = dayjs().subtract(30, 'day').format('YYYY-MM-DD')
const endDate = dayjs().format('YYYY-MM-DD')
const filterData = ref({
    list: {
        deptId: {
            name: '所属分组',
            prop: 'deptId',
            value: '',
            placeholder: '请选择所属分组',
            type: 'selectDept',
            options: [],
            defaultAttrs: {
                label: 'deptName',
                value: 'deptId'
            },
            handleFocus: (item) => {
                // if (item.options?.length) return
                // getDeptList({
                //     type: 1
                // }).then(res => {
                //     item.options = res
                // })
            },
            handleChange: (item) => {
                console.log(2222, item)
                filterData.value.list.salesId.value = ''
                filterData.value.list.salesId.options = []
            }
        },
        salesId: {
            name: '成员',
            clearOption: true,
            prop: 'saleId',
            value: '',
            placeholder: '请选择成员',
            type: 'select',
            options: [],
            defaultAttrs: {
                label: 'saleName',
                value: 'saleId'
            },
            handleFocus: (item) => {
                const value = filterData.value.list.deptId.value
                if (!value) {
                    ElMessage.warning({
                        message: '请先选择所属部门'
                    })
                    return
                }
                if (item.options?.length) return
                getSalesmanList({
                    auditStatus: 1,
                    deptId: value
                }).then(res => {
                    item.options = res
                })
            }
        },
        isMonthMode: {
            name: '月单模式',
            prop: 'type',
            value: '',
            placeholder: '请选择月单模式',
            type: 'select',
            options: [
                {
                    name: '灵活',
                    type: 3
                },
                {
                    name: '月保单',
                    type: 4
                },
                {
                    name: '即时生效',
                    type: 5
                }
            ],
            defaultAttrs: {
                label: 'name',
                value: 'type'
            },
            handleFocus: (item) => {
                // if (item.options?.length) return
                // getInsureMode({}).then(res => {
                //     item.options = res
                // })
            },
            handleChange: (item) => {
            }
        },
        insurCompanyType: {
            name: '保司',
            prop: 'insurCompanyType',
            value: '',
            placeholder: '请选择保司 ',
            type: 'select',
            options: [],
            defaultAttrs: {
                label: 'name',
                value: 'insurCompany'
            },
            handleFocus: (item) => {
                if (item.options.length) return
                getInsuranceCompany({}).then(res => {
                    item.options = res
                })
            },
            handleChange: (item) => {
            }
        },
        date: {
            name: '保单日期',
            prop: 'date',
            value: [startDate, endDate],
            initValue: [startDate, endDate],
            placeholder: '请选择保单日期',
            type: 'date',
            dateType: 'daterange',
            noClear: true,
            handleFocus: (item) => {

            },
            handleChange: (item) => {

            }
        },
        searchText: {
            name: '保单搜索',
            prop: 'searchText',
            value: '',
            placeholder: '请输入客户名称',
            type: 'input',
            inputType: 'text',
            handleFocus: (item) => {

            },
            handleChange: (item) => {

            },
            handleInput: (item) => {

            }
        },
    },
    buttonList: [
        // {
        //     icon: 'Plus',
        //     name: '新增行业',
        //     click: () => {
        //         addType.value = 'add'
        //         showAdd.value = true
        //         curItem.value = {}
        //     }
        // }
    ]
})

const pageInfo = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
})

const operationName = computed(() => {
    return (type) => {
        const map = {
            0: '加保',
            1: '减保',
            2: '撤销'
        }
        return map[type] || ''
    }
})

const tableHeader = ref([
    {
        label: '客户名称',
        prop: 'companyName',
    },
    {
        label: '商务负责人',
        prop: 'saleName',
    },
    {
        label: '所属分组',
        prop: 'deptName',
    },
    {
        label: '月单模式',
        prop: 'isMonthMode',
    },
    {
        label: '录入时间',
        prop: 'createTime',
    },
    {
        label: '操作类型',
        prop: 'operationType',
    },
    {
        label: '人数',
        prop: 'total',
    },
    // {
    //     label: '当前在保',
    //     prop: 'ensureCount'
    // }
])

const sortOrder = ref('')

const tableData = ref([])

const sortMethod = ({ prop, order }) => {
    // 0:付款时间 倒序 1:付款时间 正序 ,2:开通时间 倒序 3:开通时间 正序,4:到期时间倒序,5到期时间,正序
    switch (prop) {
        case 'paymentTime':
            if (!order) {
                sortOrder.value = ''
            } else {
                sortOrder.value = order === 'ascending' ? 1 : 0
            }
            break
        case 'productOpenTime':
            if (!order) {
                sortOrder.value = ''
            } else {
                sortOrder.value = order === 'ascending' ? 3 : 2
            }
            break
        case 'dueDate':
            if (!order) {
                sortOrder.value = ''
            } else {
                sortOrder.value = order === 'ascending' ? 5 : 4
            }
            break
    }
    getData()
}

const handleSearch = () => {
    getData()
}

const handlePageChange = () => {
    getData()
}

const toDetail = (row) => {
    router.push({
        path: '/detailPeriodInsure',
        query: {
            id: btoa(row.dealId),
            companyId: btoa(row.companyId)
        }
    })
}

const createQuery = () => {
    const query = {}
    for (const key in filterData.value.list) {
        if (filterData.value.list[key].prop === 'date') {
            query.startTime = filterData.value.list[key].value?.length ? filterData.value.list[key].value[0] : ''
            query.endTime = filterData.value.list[key].value?.length ? filterData.value.list[key].value[1] : ''
        } else {
            query[filterData.value.list[key].prop] = filterData.value.list[key].value
        }
    }
    return query
}

// 月单模式名字
const monthModeName = computed(() => {
    return (type) => {
        const cur = filterData.value.list.isMonthMode.options.find(i => i.type === type)
        return cur?.name ?? ''
    }
})

const getData = () => {
    getAddAndSubtractList({
        ...createQuery(),
        pageSize: pageInfo.value.pageSize,
        pageNum: pageInfo.value.pageNum,
        // sortOrder: sortOrder.value
    }).then(async res => {
        tableData.value = res.list
        pageInfo.value.total = res.totalCount


        // let monthModeList = []
        // if (filterData.value.list.isMonthMode.options?.length) {
        //     monthModeList = filterData.value.list.isMonthMode.options
        // } else {
        //     monthModeList = await getInsureMode({})
        //     filterData.value.list.isMonthMode.options = monthModeList
        // }
        // tableData.value.forEach(i => {
        //     const curMode = monthModeList.find(c => c.type === i.isMonthMode)
        //     i.monthModeName = ''
        //     if (curMode && i.isMonthMode) {
        //         i.monthModeName = curMode.name
        //     }
        // });
    })
}

onMounted(() => {
    getData()
})
onActivated(() => {
    getData()
})

</script>
<style lang="scss" scoped>
.type-1 {
    color: #00D679;
}
.type-0 {
    color: #FF7642;
}
</style>